package com.waijiaojun.tpo.service.weixin;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.waijiaojun.tpo.entity.weixin.WeixinPublic;
import com.waijiaojun.tpo.exception.ServerException;
import com.waijiaojun.tpo.rest.dto.TwoDimenCodeTicketBody;
import com.waijiaojun.tpo.rest.dto.WeixinUserInfoDto;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.HttpUtil;
import com.waijiaojun.tpo.utils.JsonUtil;
import com.waijiaojun.tpo.utils.Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import com.waijiaojun.tpo.comm.MyPage;
import com.waijiaojun.tpo.entity.weixin.WeixinTwoDimensionalCode;
import com.waijiaojun.tpo.repository.weixin.WeixinTwoDimensionalCodeDao;

/**
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class WeixinTwoDimensionalCodeService {

    private static Logger logger = LoggerFactory.getLogger(WeixinTwoDimensionalCodeService.class);

    @Autowired
    private WeixinTwoDimensionalCodeDao weixinTwoDimensionalCodeDao;

    @Autowired
    private WeixinAccessTokenService accessTokenService;

    public WeixinTwoDimensionalCode getById(Long id) {
        return weixinTwoDimensionalCodeDao.getById(id);
    }

    public List<WeixinTwoDimensionalCode> getAll() {
        return weixinTwoDimensionalCodeDao.getAll();
    }

    /**
     * 分页查询
     *
     * @param pageSize
     * @return
     */
    public MyPage<WeixinTwoDimensionalCode> searchPage(WeixinTwoDimensionalCode weixinTwoDimensionalCode, int currentPage, int pageSize) {
        MyPage<WeixinTwoDimensionalCode> myPage = new MyPage<WeixinTwoDimensionalCode>();

        Long count = weixinTwoDimensionalCodeDao.searchCount(weixinTwoDimensionalCode);

        int pageStart = (currentPage - 1) < 0 ? 0 : (currentPage - 1) * pageSize;
        List<WeixinTwoDimensionalCode> list = weixinTwoDimensionalCodeDao.searchPage(weixinTwoDimensionalCode, pageStart, pageSize);

        myPage.setCount(count);
        myPage.setContent(list);

        return myPage;
    }

    public void save(WeixinTwoDimensionalCode weixinTwoDimensionalCode) {
        weixinTwoDimensionalCodeDao.save(weixinTwoDimensionalCode);
    }

    public void update(WeixinTwoDimensionalCode weixinTwoDimensionalCode) {
        weixinTwoDimensionalCodeDao.update(weixinTwoDimensionalCode);
    }

    /**
     * 软删除
     */
    public void delete(Long id) {
        weixinTwoDimensionalCodeDao.delete(id);
    }

    public WeixinTwoDimensionalCode getByOpenId(String openid) {
        return weixinTwoDimensionalCodeDao.getByOpenId(openid);
    }

    /**
     * 根据用户的openid创建‘永久二维码’
     *
     * @param openid
     */
    public void createTDCode(String openid) {
        // 第一步：创建二维码ticket
        // 每次创建二维码ticket需要提供一个开发者自行设定的参数（scene_id），这里使用用户的openid作为scene_id。

        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessTokenService.getAccessToken();
        String reqBody = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + openid + "\"}}}";
        TwoDimenCodeTicketBody bean = null;
        logger.info("----------------------------------------\n--- 第一步：创建二维码");
        try {
            String body = HttpUtil.httpPost(url, reqBody);
            bean = JsonUtil.toObject(body, TwoDimenCodeTicketBody.class);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ServerException("读取用户信息错误,格式错误：" + e.getMessage());
        }

        String tdCodePath = null;
        if (bean != null && StringUtils.isNotBlank(bean.getTicket())) {
            tdCodePath = HttpUtil.getTDCode(bean.getTicket(), openid);
        }

        if (tdCodePath != null) {
            WeixinTwoDimensionalCode code = new WeixinTwoDimensionalCode();
            code.setOpenid(openid);
            code.setImageUrl(tdCodePath);
            Date now = new Date();
            code.setCreateDate(now);
            code.setUpdateDate(now);
            code.setSceneStr(openid);
            code.setWeixinPublicId(Constants.publicId);
            weixinTwoDimensionalCodeDao.save(code);
        }

    }
}
